import antlr.RecognitionException;
import lk.uom.cse.adarchi.dlxasm.aLexer;
import lk.uom.cse.adarchi.dlxasm.aParser;
import optimizer.Optimizer;
import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;

import java.io.*;
import java.util.logging.Logger;

public class Main {

    public final static Logger log = Logger.getLogger(Main.class.getName());
    public static void main(String[] args) throws RecognitionException {
        try {

            log.info("Initializing Parser: start parsing " + args[0]);
            aLexer lexer = new aLexer(new ANTLRFileStream(args[0]));
            aParser parser = new aParser(new CommonTokenStream(lexer));
            log.info("Loading DLX assembly Rules...");
            StringTemplateGroup stg = new StringTemplateGroup(new FileReader(Main.class.getResource("DLX.stg").getFile()));
            parser.setTemplateLib(stg);

            log.info("Start Parsing Program...");
            aParser.program_return program_return = parser.program();
            StringTemplate st = (StringTemplate) program_return.getTemplate();
            File file = new File("asem_unoptimized.txt");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(st.toString());
			bw.close();
            log.info("File Created " + file.getAbsolutePath() );
            log.info("[Completed] Unoptimized code generated");
            Optimizer optimizer = new Optimizer(st.toString());
            File file2 = new File("asem_optimized.txt");
			if (!file.exists()) {
				file.createNewFile();
			}
            fw = new FileWriter(file2.getAbsoluteFile());
			bw = new BufferedWriter(fw);
			bw.write(optimizer.getOptimizedCode());
			bw.close();
            log.info("File Created " + file2.getAbsolutePath() );
            log.info("[Completed] Optimized code generated");
            log.info("[Completed] File parsing completed");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (org.antlr.runtime.RecognitionException e) {
            e.printStackTrace();
        }
    }
}
